package cn.javablog.controller;


import cn.javablog.Vo.BlogVo;
import cn.javablog.Vo.PageBlogVo;
import cn.javablog.common.lang.Result;
import cn.javablog.entity.TBlog;
import cn.javablog.service.TBlogService;
import cn.javablog.util.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AllenYe
 * @since 2020-08-31
 */
@RestController
@RequestMapping("/blog")
@ConfigurationProperties(prefix = "server")
public class TBlogController {
    @Value("${server.port}")
    private Integer port;
    @Autowired
    private TBlogService tBlogService;
    /**
     * 博客查询分页
     * @param pageBlogVo
     * @return
     */
//    @RequiresAuthentication
    @PostMapping("/list")
    public Result list(@RequestBody PageBlogVo pageBlogVo){
        Page page = new Page(pageBlogVo.getPageCurrent() == 0 ? 1 : pageBlogVo.getPageCurrent(),pageBlogVo.getPageSize() == 0 ? 10 : pageBlogVo.getPageSize());
        QueryWrapper<TBlog> wrapper = new QueryWrapper<>();
        wrapper.like("title",pageBlogVo.getTitle());
        wrapper.eq("user_id",pageBlogVo.getUser_id());
        wrapper.like("type_id",pageBlogVo.getType_id());
        wrapper.like("tag_ids",pageBlogVo.getTag_ids());
        wrapper.eq("flag",true);
        wrapper.or().orderByDesc("create_time");
        IPage page1 = tBlogService.page(page, wrapper);
        return Result.succ(page1);
    }

    /**
     * 添加博客
     * @param blogVo
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/add")
    public Result add(@Validated @RequestBody BlogVo blogVo){
        int addInt = tBlogService.addBlog(blogVo);
        if(addInt>0){
            return Result.succ("添加成功",null);
        }else{
            return Result.fail("添加失败",null);
        }
    }

    /**
     * 修改博客
     * @param blogVo
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result editBlog(@Validated @RequestBody BlogVo blogVo){
        if(tBlogService.editBlog(blogVo)>0){
            return Result.succ("修改成功",null);
        }else{
            return Result.fail("修改失败",null);
        }
    }
    /**
     * 删除博客
     * @param id
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/del")
    public Result del(@RequestParam int id){
        int blogDel = tBlogService.delBlog(id);
        if(blogDel>0){
            return Result.succ("删除成功",null);
        }else{
            return Result.fail("删除失败",null);
        }
    }

    /**
     * 文件上传到服务器，返回路径
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequiresAuthentication
    @RequestMapping("/imageUpload")
    public Result imageUpload(@RequestBody MultipartFile file, HttpServletRequest request) throws IOException {
        if(null != file) {
            String suffix  = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
            if(!(FileUtil.IMG_TYPE_DMG.equals(suffix.toUpperCase()) ||
                    FileUtil.IMG_TYPE_GIF.equals(suffix.toUpperCase()) ||
                    FileUtil.IMG_TYPE_JPEG.equals(suffix.toUpperCase()) ||
                    FileUtil.IMG_TYPE_JPG.equals(suffix.toUpperCase()) ||
                    FileUtil.IMG_TYPE_PNG.equals(suffix.toUpperCase()) ||
                    FileUtil.IMG_TYPE_SVG.equals(suffix.toUpperCase()))){
                return Result.fail("文件格式错误");
            }else{
                File fileMkdir=new File("src/main/resources/static/imageResource");
                if(!fileMkdir.exists()) {
                    fileMkdir.mkdir();
                }
                String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                //当前年月日
                String day = sdf.format(new Date());
                Date date = new Date();
                long time = date.getTime();
                System.out.println(port);
                //文档下载地址
                String str = request.getRequestURL().toString();
                String httpUrl = str.substring(0,str.indexOf(port.toString())+5);
                String FileUrl = fileMkdir.getPath().substring(fileMkdir.getPath().lastIndexOf("\\")+1);
                String url =httpUrl+ FileUrl + "/" + day + time + fileName;
                FileOutputStream os = new FileOutputStream(fileMkdir.getPath() + "\\" + day + time + fileName);
                InputStream in = file.getInputStream();
                int b = 0;
                while((b=in.read())!=-1){ //读取文件
                    os.write(b);
                }
                os.flush(); //关闭流
                in.close();
                os.close();
                Map<String,String> map = new HashMap();
                map.put("url",url);
                return Result.succ("文件上传成功",map);
            }
        }else{
            return Result.fail("文件不能为空");
        }
    }
}
